import urllib
import BeautifulSoup

class Querier:
    def __init__(self):
        self.shortName= "psydb"
        self.longName = "Psychedelic Mind Expander"
        self.provides=['album_front_large', 'album_front_small']

        self.baseURL = "http://pme.no-ip.org/pme2000/labels_search.asp?strMode=ADV"
        self.imageURL = "http://pme.no-ip.org/pme2000/image.asp?strPicName="

    def process(self, item):
        artist = item.artist
        album = item.album

        if (artist):
            terms = {'strSearchArtist':artist.encode("UTF-8"), 'strSearchRelease':album.encode("UTF-8")}
        else:
            terms = {'strSearchRelease':album.encode("UTF-8")}

        params = urllib.urlencode(terms)

        data = urllib.urlopen (self.baseURL, params).read ()
        soup = BeautifulSoup.BeautifulSoup (data)

        try:
            m = soup("td", {'class':'T1'})[0]('a')[0].get('href')
        except IndexError:
            return []

        return self.getReleasePage(m)

    def getReleasePage(self,url):
        ret = []
        data = urllib.urlopen (url)
        soup = BeautifulSoup.BeautifulSoup (data)

        m = soup("td", {'class':'T1'})
        # a href="javascript:void(0)"
        small=m[0]('a')[0]('img')[0].get('src')
        ret.append(small)
        large=m[0]('a')[0].get('onclick')
        large = large.strip("showPicture(").strip("); return false;")
        large = large.split(",")
        largeImg = large[0].replace("'", "")

        useLarge=self.imageURL+largeImg
        ret.append(useLarge)

        return ret

